package com.fingard.dsp.bank.directbank.unionpay01.util;

import org.apache.commons.lang3.StringUtils;

import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.itrus.cryptorole.Sender;
import com.itrus.cryptorole.bc.SenderBcImpl;
import com.itrus.util.Base64;

public class UlpayRaTools {
	public static String addSignatrue(String orgMsg,ActSetItem actItem) throws Exception{
//		String signLabel = "<SIGNED_MSG>signedMsg</SIGNED_MSG>";
//		String signLabelEmpty = "<SIGNED_MSG />";
		StringBuffer signBuffer = new StringBuffer("<SIGNED_MSG>").append(UlpayRaTools.mercSign(orgMsg, actItem)).append("</SIGNED_MSG>");
		return signBuffer.toString();
//		return orgMsg.replace(signLabelEmpty, signBuffer.toString());
	}
	
    /**
     * 签名方法
     * @param oriData 原文信息
     * @return 签名结果
     */
    public static  String mercSign(String oriData,ActSetItem actItem)throws Exception{
        String signData = "";
        if(StringUtils.isBlank(oriData)){
            throw new IllegalArgumentException("请求签名数据不能为空");
        }
        if(StringUtils.isBlank(actItem.merchantId)){
            throw new IllegalArgumentException("签名时商户号不能为空");
        }
        String mercCertPath = actItem.ownKeyStorePath;
        if (null == mercCertPath || "".equals(mercCertPath)) {
            throw new IllegalArgumentException("mercCertPath IS NOT NULL");
        }

        String mercCertPass =  actItem.ownKeyPassword;
        if (null == mercCertPass || "".equals(mercCertPass)) {
            throw new IllegalArgumentException("mercCertPass IS NOT NULL");
        }
        try {
        	Sender s = new SenderBcImpl();
            s.initCertWithKey(mercCertPath, mercCertPass.toCharArray());
            byte[] p7dtach = s.signMessage(oriData.getBytes("UTF-8"));
            signData = Base64.encode(p7dtach);
        } catch (Exception e) {
        	e.printStackTrace();
            throw new Exception("数据签名失败",e);
        }
        return signData;
    }
}
